/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.web.config.spring;

import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
import org.springframework.beans.factory.xml.ParserContext;
import org.vacoor.nothing.web.util.SettingsUtils;
import org.w3c.dom.Element;

/**
 * @author vacoor
 */
/*
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass" value="org.vacoor.nothing.web.util.SettingsUtils"/>
<property name="targetMethod" value="setConfigurationManager"/>
<property name="arguments" ref="configurationManager" />
</bean>
*/
public class CustomNamespaceHandler extends NamespaceHandlerSupport {
    private static final String TARGET_CLASS = SettingsUtils.class.getName();
    private static final String TARGET_METHOD = "setConfigurationManager";

    @Override
    public void init() {
        registerBeanDefinitionParser("config", new CustomBeanDefinitionParser());
    }

    class CustomBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
        @Override
        protected Class<?> getBeanClass(Element element) {
            return MethodInvokingFactoryBean.class;
        }

        @Override
        protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
            String bind = element.getAttribute("bind-ref");
            builder.addPropertyValue("targetClass", TARGET_CLASS)
                    .addPropertyValue("targetMethod", TARGET_METHOD)
                    .addPropertyReference("arguments", bind);


            super.doParse(element, parserContext, builder);
        }
    }
}
